<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 供应商接算
 * Class Controller_Admin_Finance_Supplier_Settle
 */
class Controller_Admin_Finance_Supplier_Settle extends Stourweb_Controller
{

    function before()
    {
        parent::before();
        $this->assign('prefix_url','finance/admin/finance/supplier');
    }

    //结算审批
    public function action_aduit()
    {
        $action = $this->params['action'];
        $modules = DB::select('id', 'modulename', 'pinyin','maintable','correct')
            ->from('model')
            ->where('is_orderable', '=', 1)
            ->execute()
            ->as_array();
        $this->assign('modules',$modules);
        if(!$action)
        {
            $order_status=Model_Member_Order::$orderStatus;
            $channel_list = St_Functions::get_ota_channel(null,true);

            $this->assign('channel_list', $channel_list);
            $this->assign('order_status',json_encode($order_status));
            $this->display('admin/finance/supplier/settle/aduit');
        }
        switch ($action)
        {
            case 'read':
                $this->show_list();
                break;
        }
    }

    /**
     * @function 记录列表
     */
    private function show_list()
    {
        $start = $_GET['start'];
        $limit = $_GET['limit'];
        $status = $_GET['status'];
        $keyword = $_GET['keyword'];
        $typeid = $_GET['type_id'];
        $channel_id = $_GET['channel_id'];
        $startdate = Arr::get($_GET,'startdate');
        $enddate = Arr::get($_GET,'enddate');

        $where = "a.id>0";
        if($status)
        {
            if($status ==2 || $status == 1){
                $where .= " and (a.status=$status and b.status=5)";
            }
            //不可结算
            else{
                $where .= " and b.status!=5";
            }

        }
        if($keyword)
        {
            $where .=" and (b.productname like '%$keyword%' or c.suppliername like '%$keyword%' or a.ordersn like '%$keyword%')";
        }
        if($typeid)
        {
            $where .=" and (b.typeid = '$typeid') ";
        }
        //付款时间
        if($startdate)
        {
            $where .=" and (b.paytime>=".strtotime($startdate).") ";
        }
        //付款时间
        if($enddate)
        {
            $where .=" and (b.paytime<=".strtotime($enddate).") ";
        }
        if($channel_id){
            $where .= " and b.channel_id={$channel_id} ";
        }
        $sql = "select a.*,b.productname,b.status as order_status,b.typeid,c.suppliername,d.total_price as order_total_price,d.privileg_price AS order_privileg_price,d.platform_commission from sline_supplier_brokerage as a ";
        $sql.= "LEFT JOIN sline_member_order as b on(a.ordersn=b.ordersn) ";
        $sql.= "LEFT JOIN sline_supplier as c on(a.supplierlist=c.id) ";
        $sql.= "LEFT JOIN sline_member_order_compute as d on(b.id=d.order_id) ";
        $sql.= "WHERE {$where} order by a.addtime desc ";
        $total = DB::query(1,$sql)->execute()->count();
        $sql.= "limit {$start},{$limit}";
        $list = DB::query(1,$sql)->execute()->as_array();

        foreach ($list as &$l)
        {
            $l['order_price'] = $l['platform_commission'];
            $l['addtime'] = date('Y-m-d H:i:s',$l['addtime']);
            $l['open_price'] = $l['brokerage'] - $l['finish_brokerage'] ;
            //产品类型
            $l['typename'] = DB::select('modulename')
                ->from('model')
                ->where('is_orderable', '=', 1)
                ->and_where('id','=',$l['typeid'])
                ->execute()
                ->get('modulename');

        }
        unset($l);
        echo  json_encode(array('total'=>$total,'lists'=>$list));

    }


    //结算确认
    public function action_change_status()
    {
        $id = $_GET['id'];
        $info = DB::select()->from('supplier_brokerage')
            ->where('id','=',$id)->execute()->current();
        $info['open_price'] = $info['brokerage'] - $info['finish_brokerage'] ;
        $this->assign('info',$info);
        $this->display('admin/finance/supplier/settle/dialog_change_status');

    }


    //保存结算信息
    public function action_ajax_change_status()
    {
        $id = $_POST['id'];
        $open_price = $_POST['open_price'];
        $info = DB::select()->from('supplier_brokerage')
            ->where('id','=',$id)->execute()->current();
        if($info['status']!=1)
        {
            exit(json_encode(array('status'=>0)));
        }
        if($info['finish_brokerage'])
        {
            $info['open_price'] = $info['brokerage'] - $info['finish_brokerage'] ;
            if($open_price!=$info['open_price'])
            {
                exit(json_encode(array('status'=>0)));
            }
            $open_price += $info['finish_brokerage'];
        }
        $data = array(
            'finish_brokerage'=>$open_price,
            'modtime'=>time(),
        );
        if($open_price>$info['brokerage'])
        {
            exit(json_encode(array('status'=>0)));
        }
        if($open_price==$info['brokerage'])
        {
            $data['status'] = 2;
        }
        $rsn = DB::update('supplier_brokerage')->set($data)->where('id','=',$id)->execute();
        if($rsn)
        {
            exit(json_encode(array('status'=>1)));
        }

    }



    /*
     * 生成excel页面
     * */
    public function action_excel()
    {
        $this->assign('params',$_GET);
        $this->assign('statusnames', Model_Member_Order::$order_status);
        $this->display('admin/finance/supplier/settle/excel');
    }

    public function action_genexcel()
    {
        $timetype = $this->params['timetype'];
        $starttime = empty($_GET['starttime'])? null:strtotime($_GET['starttime'].' 00:00:00');
        $endtime =empty($_GET['endtime'])?null: strtotime($_GET['endtime'].' 23:59:59');
        $time_arr = array();

        switch ($timetype)
        {
            case 1:
                $time_arr = St_Functions::back_get_time_range(1);
                break;
            case 2:
                $time_arr = St_Functions::back_get_time_range(2);
                break;
            case 3:
                $time_arr = St_Functions::back_get_time_range(3);
                break;
            case 5:
                $time_arr = St_Functions::back_get_time_range(5);
                break;
            case 6:
                $time_arr = array($starttime, $endtime);
                break;
        }

        $where  = " a.addtime > $time_arr[0] and  a.addtime < $time_arr[1] " ;
        $sql="select a.*,b.productname,b.status as order_status,b.typeid,c.suppliername from sline_supplier_brokerage as a LEFT JOIN sline_member_order as b  on a.ordersn=b.ordersn  LEFT JOIN sline_supplier as c  on  a.supplierlist=c.id WHERE $where order by a.addtime desc";

        $info = DB::query(1,$sql)->execute()->as_array();
        $this->gene_excel($info);


    }

    protected function gene_excel($order_list)
    {
        $order_status = Model_Member_Order::$orderStatus;

        $titles = array('付款日期','订单号','产品类型','产品名称','营业收入','订单状态','供应商','结算金额','结算状态');
        $rows = array();
        foreach ($order_list as $row)
        {

            if($row['status']==1 && $row['order_status'] == 5)
            {
                $row['status'] = '未结算';
            }
            else if($row['status']==2 && $row['order_status'] == 5) {
                $row['status'] = '已结算';
            }
            else{
                $row['status'] = '不可结算';
            }
            //产品类型
            $row['typename'] = DB::select('modulename')
                ->from('model')
                ->where('is_orderable', '=', 1)
                ->and_where('id','=',$row['typeid'])
                ->execute()
                ->get('modulename');
            $rows[] = array(
                date('Y-m-d H:i:s',$row['addtime']),
                $row['ordersn'],
                $row['typename'],
                $row['productname'],
                $row['order_price'],
                $order_status[$row['order_status']],
                $row['suppliername'],
                $row['brokerage'],
                $row['status']
            );
        }
        $td_width = array(25,25,10,40,15,15,30,15,15);
        $col_style = array('string','string','string','string','string','string','string','string','string');
        St_File::export_excel($rows, $titles, $td_width, $col_style);


    }

}